package com.pkdl.forms;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;

import com.pkdl.dao.NguoiDungDAO;
import com.pkdl.datepicker.JCalendar;
import com.pkdl.dto.NguoiDungDTO;
import com.pkdl.enums.LoaiNguoiDung;
import com.pkdl.helpers.Validator;
import com.pkdl.tables.TableNguoiDung;

@SuppressWarnings("serial")
public class DlgQuanLyNguoiDung extends JDialog {

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			DlgQuanLyNguoiDung dialog = new DlgQuanLyNguoiDung(null, true);
			dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private JTable tblData;
	private JTextField txtMaND;
	private JTextField txtHoTen;
	private JTextField txtNoiSinh;
	private JTextField txtDTBan;
	private JTextField txtDTDD;
	private JTextField txtDiaChi;
	private JTextField txtLuong;
	private JTextField txtChuyenMon;
	private JTextField txtEmail;
	private JComboBox cbxLoaiNguoiDung;
	private JCalendar txtNgaySinh = null;
	private JCalendar txtNgayVaoLam = null;
	private JPanel pnlCalNgaySinh;
	private JPanel pnlCalNgayVaoLam;
	private JLabel lblLuongFormated;
	private NguoiDungDAO ndDAO;
	private JRadioButton rdbtnNam;
	private JRadioButton rdbtnNu;

	/**
	 * Create the dialog.
	 */
	public DlgQuanLyNguoiDung(Frame parent, boolean modal) {
		super(parent, modal);
		this.setTitle("Quan ly nguoi dung");
		this.setBounds(100, 100, 1146, 662);
		this.setLocationRelativeTo(null);
		this.getContentPane().setLayout(new BorderLayout());
		{
			JPanel panel = new JPanel();
			this.getContentPane().add(panel, BorderLayout.CENTER);
			panel.setLayout(new BorderLayout(0, 0));
			{
				JPanel panel_1 = new JPanel();
				panel_1.setPreferredSize(new Dimension(452, 10));
				panel.add(panel_1, BorderLayout.WEST);
				panel_1.setLayout(new BorderLayout(0, 0));
				{
					JPanel panel_2 = new JPanel();
					panel_2.setBackground(SystemColor.textHighlight);
					panel_1.add(panel_2, BorderLayout.NORTH);
					panel_2.setLayout(new BorderLayout(0, 0));
					{
						JLabel lblNewLabel = new JLabel(
								"  Danh s\u00E1ch ng\u01B0\u1EDDi d\u00F9ng");
						lblNewLabel.setHorizontalAlignment(SwingConstants.LEFT);
						lblNewLabel.setForeground(Color.WHITE);
						lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 18));
						lblNewLabel.setPreferredSize(new Dimension(46, 32));
						panel_2.add(lblNewLabel, BorderLayout.CENTER);
					}
				}
				{
					JScrollPane scrollPane = new JScrollPane();
					panel_1.add(scrollPane, BorderLayout.CENTER);
					{
						this.tblData = new JTable();
						this.tblData.addMouseListener(new MouseAdapter() {
							@Override
							public void mousePressed(MouseEvent evt) {
								DlgQuanLyNguoiDung.this.actionSelect(evt);
							}
						});
						this.tblData.setFillsViewportHeight(true);
						this.tblData.setModel(new DefaultTableModel(
								new Object[][] { { null, null, null },
										{ null, null, null },
										{ null, null, null }, }, new String[] {
										"New column", "New column",
										"New column" }));
						scrollPane.setViewportView(this.tblData);
					}
				}
			}
			{
				JPanel panel_1 = new JPanel();
				panel.add(panel_1, BorderLayout.CENTER);
				panel_1.setLayout(null);

				JLabel lblNewLabel_1 = new JLabel(
						"Th\u00F4ng tin ng\u01B0\u1EDDi d\u00F9ng");
				lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 18));
				lblNewLabel_1.setForeground(new Color(0, 128, 0));
				lblNewLabel_1.setBounds(10, 0, 287, 31);
				panel_1.add(lblNewLabel_1);

				JLabel lblNewLabel_2 = new JLabel("M\u00E3 ND");
				lblNewLabel_2.setBounds(34, 57, 46, 14);
				panel_1.add(lblNewLabel_2);

				this.txtMaND = new JTextField();
				this.txtMaND.setBounds(118, 54, 86, 20);
				panel_1.add(this.txtMaND);
				this.txtMaND.setColumns(10);
				{
					JLabel lblTnDv = new JLabel("Lo\u1EA1i ND");
					lblTnDv.setBounds(34, 85, 46, 14);
					panel_1.add(lblTnDv);
				}

				JButton btnLuu = new JButton("L\u01B0u");
				btnLuu.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						DlgQuanLyNguoiDung.this.actionLuu();
					}
				});
				btnLuu.setIcon(new ImageIcon(DlgQuanLyDichVu.class
						.getResource("/com/pkdl/resources/45.png")));
				btnLuu.setBounds(559, 573, 89, 23);
				panel_1.add(btnLuu);

				JButton btnXoa = new JButton("X\u00F3a");
				btnXoa.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						DlgQuanLyNguoiDung.this.actionDelete();
					}
				});
				btnXoa.setIcon(new ImageIcon(DlgQuanLyDichVu.class
						.getResource("/com/pkdl/resources/001_29.png")));
				btnXoa.setBounds(460, 573, 89, 23);
				panel_1.add(btnXoa);

				JButton btnThemMoi = new JButton("Th\u00EAm m\u1EDBi");
				btnThemMoi.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						DlgQuanLyNguoiDung.this.resetFields();
					}
				});
				btnThemMoi.setIcon(new ImageIcon(DlgQuanLyDichVu.class
						.getResource("/com/pkdl/resources/Eraser-icon.png")));
				btnThemMoi.setBounds(338, 573, 112, 23);
				panel_1.add(btnThemMoi);
				{
					JLabel label = new JLabel("H\u1ECD t\u00EAn");
					label.setBounds(34, 115, 46, 14);
					panel_1.add(label);
				}
				{
					this.txtHoTen = new JTextField();
					this.txtHoTen.setColumns(10);
					this.txtHoTen.setBounds(118, 112, 219, 20);
					panel_1.add(this.txtHoTen);
				}
				{
					JLabel label = new JLabel("Ng\u00E0y sinh");
					label.setBounds(34, 216, 74, 14);
					panel_1.add(label);
				}
				{
					JLabel label = new JLabel("Gi\u1EDBi t\u00EDnh");
					label.setBounds(34, 330, 65, 14);
					panel_1.add(label);
				}
				{
					this.rdbtnNam = new JRadioButton("Nam");
					this.rdbtnNam.setSelected(true);
					this.rdbtnNam.setBounds(118, 326, 65, 23);
					panel_1.add(this.rdbtnNam);
				}
				{
					this.rdbtnNu = new JRadioButton("N\u1EEF");
					this.rdbtnNu.setBounds(196, 326, 65, 23);
					panel_1.add(this.rdbtnNu);
				}
				{
					JLabel lblNiSinh = new JLabel("N\u01A1i sinh");
					lblNiSinh.setBounds(34, 358, 74, 14);
					panel_1.add(lblNiSinh);
				}
				{
					this.txtNoiSinh = new JTextField();
					this.txtNoiSinh.setColumns(10);
					this.txtNoiSinh.setBounds(118, 356, 364, 20);
					panel_1.add(this.txtNoiSinh);
				}
				{
					JLabel lblNi = new JLabel("\u0110\u1ECBa ch\u1EC9");
					lblNi.setBounds(34, 385, 46, 14);
					panel_1.add(lblNi);
				}
				{
					JLabel lbltd = new JLabel("\u0110TD\u0110");
					lbltd.setBounds(34, 415, 46, 14);
					panel_1.add(lbltd);
				}
				{
					JLabel lbltBn = new JLabel("\u0110T b\u00E0n");
					lbltBn.setBounds(34, 443, 74, 14);
					panel_1.add(lbltBn);
				}
				{
					this.txtDTBan = new JTextField();
					this.txtDTBan.setColumns(10);
					this.txtDTBan.setBounds(118, 440, 157, 20);
					panel_1.add(this.txtDTBan);
				}
				{
					this.txtDTDD = new JTextField();
					this.txtDTDD.setColumns(10);
					this.txtDTDD.setBounds(118, 412, 157, 20);
					panel_1.add(this.txtDTDD);
				}
				{
					this.txtDiaChi = new JTextField();
					this.txtDiaChi.setColumns(10);
					this.txtDiaChi.setBounds(118, 382, 364, 20);
					panel_1.add(this.txtDiaChi);
				}
				{
					JLabel lblEmail = new JLabel("Email");
					lblEmail.setBounds(34, 471, 46, 14);
					panel_1.add(lblEmail);
				}
				{
					JLabel lblChuynMn = new JLabel("Chuy\u00EAn m\u00F4n");
					lblChuynMn.setBounds(34, 499, 78, 14);
					panel_1.add(lblChuynMn);
				}
				{
					JLabel lblLng = new JLabel("L\u01B0\u01A1ng");
					lblLng.setBounds(34, 529, 46, 14);
					panel_1.add(lblLng);
				}
				{
					this.txtLuong = new JTextField();
					this.txtLuong.addKeyListener(new KeyAdapter() {
						@Override
						public void keyReleased(KeyEvent ke) {
							char c = ke.getKeyChar();
							if ((!(Character.isDigit(c))) && (c != '\b')) {
								ke.consume();
							} else {
								DlgQuanLyNguoiDung.this.formatGia();
							}
						}
					});
					this.txtLuong.setColumns(10);
					this.txtLuong.setBounds(118, 526, 157, 20);
					panel_1.add(this.txtLuong);
				}
				{
					this.txtChuyenMon = new JTextField();
					this.txtChuyenMon.setColumns(10);
					this.txtChuyenMon.setBounds(118, 496, 287, 20);
					panel_1.add(this.txtChuyenMon);
				}
				{
					this.txtEmail = new JTextField();
					this.txtEmail.setColumns(10);
					this.txtEmail.setBounds(118, 468, 219, 20);
					panel_1.add(this.txtEmail);
				}

				this.cbxLoaiNguoiDung = new JComboBox(
						LoaiNguoiDung.getAllItems());
				this.cbxLoaiNguoiDung.setBounds(118, 82, 157, 20);
				panel_1.add(this.cbxLoaiNguoiDung);

				this.pnlCalNgaySinh = new JPanel();
				this.pnlCalNgaySinh.setBounds(118, 143, 219, 176);
				panel_1.add(this.pnlCalNgaySinh);
				this.pnlCalNgaySinh.setLayout(new BorderLayout(0, 0));

				JLabel lblNgyVoLm = new JLabel("Ng\u00E0y v\u00E0o l\u00E0m");
				lblNgyVoLm.setHorizontalAlignment(SwingConstants.RIGHT);
				lblNgyVoLm.setBounds(347, 216, 86, 14);
				panel_1.add(lblNgyVoLm);

				this.pnlCalNgayVaoLam = new JPanel();
				this.pnlCalNgayVaoLam.setBounds(443, 143, 219, 176);
				panel_1.add(this.pnlCalNgayVaoLam);
				this.pnlCalNgayVaoLam.setLayout(new BorderLayout(0, 0));
				{
					this.lblLuongFormated = new JLabel("");
					this.lblLuongFormated.setBounds(281, 529, 124, 14);
					panel_1.add(this.lblLuongFormated);
				}
			}
		}
		this.LoadNgaySinh();
		this.LoadNgayVaoLam();
		this.loadData();
	}

	/**
	 * Delete item
	 */
	private void actionDelete() {
		if (this.txtMaND.getText().trim().equals("")) {
			JOptionPane.showMessageDialog(null, "Vui long chon dong de xoa",
					"Announcement", JOptionPane.ERROR_MESSAGE);
			return;
		}
		this.ndDAO = new NguoiDungDAO();
		if (this.ndDAO.delete(this.txtMaND.getText())) {
			this.loadData();
			this.resetFields();
			JOptionPane.showMessageDialog(null, "Xoa du lieu thanh cong",
					"Announcement", JOptionPane.INFORMATION_MESSAGE);
		} else {
			JOptionPane.showMessageDialog(null, "Khong the xoa du lieu",
					"Announcement", JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * Them moi, xoa, cap nhat danh sach thuoc
	 */
	private void actionLuu() {
		AtomicReference<Object> errText = new AtomicReference<Object>("");
		if (!this.validateInputData(errText)) {
			JOptionPane.showMessageDialog(null, errText.get(), "Announcement",
					JOptionPane.ERROR_MESSAGE);
			return;
		}

		this.ndDAO = new NguoiDungDAO();

		// Them moi
		if (this.txtMaND.isEditable()) {
			NguoiDungDTO item = new NguoiDungDTO();
			item.setMaNguoiDung(this.txtMaND.getText());
			item.setLoaiNguoiDung(String.valueOf(this.cbxLoaiNguoiDung
					.getSelectedItem()));
			item.setHoTen(this.txtHoTen.getText());
			item.setGioiTinh(this.rdbtnNam.isSelected() ? true : false);

			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.MONTH, this.txtNgaySinh.getMonthChooser()
					.getMonth());
			cal.set(Calendar.DATE, this.txtNgaySinh.getDayChooser().getDay());
			cal.set(Calendar.YEAR, this.txtNgaySinh.getYearChooser().getYear());

			item.setNgaySinh(cal.getTime());
			item.setNoiSinh(this.txtNoiSinh.getText());

			cal = Calendar.getInstance();
			cal.set(Calendar.MONTH, this.txtNgayVaoLam.getMonthChooser()
					.getMonth());
			cal.set(Calendar.DATE, this.txtNgayVaoLam.getDayChooser().getDay());
			cal.set(Calendar.YEAR, this.txtNgayVaoLam.getYearChooser()
					.getYear());

			item.setNgayVaoLam(cal.getTime());
			item.setNoiOHienTai(this.txtDiaChi.getText());
			item.setDTDD(this.txtDTDD.getText());
			item.setDTNha(this.txtDTBan.getText());
			item.setEmail(this.txtEmail.getText());
			item.setChuyenMon(this.txtChuyenMon.getText());
			item.setMatKhau("123");
			item.setLuong(Long.parseLong(this.txtLuong.getText()));

			if (this.ndDAO.insert(item)) {
				this.loadData();
				this.resetFields();
				JOptionPane.showMessageDialog(null, "Them du lieu thanh cong",
						"Announcement", JOptionPane.INFORMATION_MESSAGE);
			} else {
				JOptionPane.showMessageDialog(null, "Khong the them du lieu",
						"Announcement", JOptionPane.ERROR_MESSAGE);
			}

		} else {
			// Cap nhat
			NguoiDungDTO item = this.ndDAO.selectById(this.txtMaND.getText());

			item.setLoaiNguoiDung(String.valueOf(this.cbxLoaiNguoiDung
					.getSelectedItem()));
			item.setHoTen(this.txtHoTen.getText());
			item.setGioiTinh(this.rdbtnNam.isSelected() ? true : false);

			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.MONTH, this.txtNgaySinh.getMonthChooser()
					.getMonth());
			cal.set(Calendar.DATE, this.txtNgaySinh.getDayChooser().getDay());
			cal.set(Calendar.YEAR, this.txtNgaySinh.getYearChooser().getYear());

			item.setNgaySinh(cal.getTime());
			item.setNoiSinh(this.txtNoiSinh.getText());

			cal = Calendar.getInstance();
			cal.set(Calendar.MONTH, this.txtNgayVaoLam.getMonthChooser()
					.getMonth());
			cal.set(Calendar.DATE, this.txtNgayVaoLam.getDayChooser().getDay());
			cal.set(Calendar.YEAR, this.txtNgayVaoLam.getYearChooser()
					.getYear());

			item.setNgayVaoLam(cal.getTime());
			item.setNoiOHienTai(this.txtDiaChi.getText());
			item.setDTDD(this.txtDTDD.getText());
			item.setDTNha(this.txtDTBan.getText());
			item.setEmail(this.txtEmail.getText());
			item.setChuyenMon(this.txtChuyenMon.getText());
			item.setMatKhau("123");
			item.setLuong(Long.parseLong(this.txtLuong.getText()));

			if (this.ndDAO.update(item)) {
				this.loadData();
				JOptionPane.showMessageDialog(null,
						"Cap nhat du lieu thanh cong", "Announcement",
						JOptionPane.INFORMATION_MESSAGE);
			} else {
				JOptionPane.showMessageDialog(null,
						"Khong the cap nhat du lieu", "Announcement",
						JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	/**
	 * Lua chon item trong danh sach
	 */
	private void actionSelect(MouseEvent evt) {
		int modifiers = evt.getModifiers();
		if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
			if (this.tblData.getSelectedRow() == -1) {
				return;
			}

			if (this.tblData.getValueAt(this.tblData.getSelectedRow(), 0) == null) {
				return;
			}

			if (evt.getClickCount() == 1) {
				this.ndDAO = new NguoiDungDAO();
				String id = ((JLabel) this.tblData.getValueAt(
						this.tblData.getSelectedRow(), 0)).getName().trim();
				NguoiDungDTO item = this.ndDAO.selectById(id);
				this.txtMaND.setText(String.valueOf(item.getMaNguoiDung()));
				this.cbxLoaiNguoiDung.setSelectedItem(item.getLoaiNguoiDung());
				this.txtHoTen.setText(item.getHoTen());
				if (item.getGioiTinh()) {
					this.rdbtnNam.setSelected(true);
					this.rdbtnNu.setSelected(false);
				} else {
					this.rdbtnNam.setSelected(false);
					this.rdbtnNu.setSelected(true);
				}
				this.txtNgaySinh.setDate(item.getNgaySinh());
				this.txtNoiSinh.setText(item.getNoiSinh());
				this.txtNgayVaoLam.setDate(item.getNgayVaoLam());
				this.txtDiaChi.setText(item.getNoiOHienTai());
				this.txtDTDD.setText(item.getDTDD());
				this.txtDTBan.setText(item.getDTNha());
				this.txtEmail.setText(item.getEmail());
				this.txtChuyenMon.setText(item.getChuyenMon());
				this.txtLuong.setText(String.valueOf(item.getLuong()));

				// Important to separate update and insert new
				this.txtMaND.setEditable(false);
			}
		}
	}

	/**
	 * Format gia
	 */
	private void formatGia() {
		if (!this.txtLuong.getText().trim().equals("")) {
			NumberFormat numberFormatter = new DecimalFormat("#,###,###");
			String formattedNumber = numberFormatter.format(Long
					.parseLong(this.txtLuong.getText()));
			this.lblLuongFormated.setText(formattedNumber);
		} else {
			this.lblLuongFormated.setText("");
		}
	}

	/**
	 * Load danh sach thuoc
	 */
	private void loadData() {
		this.ndDAO = new NguoiDungDAO();
		List<NguoiDungDTO> ds = this.ndDAO.selectAll();
		TableNguoiDung table = new TableNguoiDung(ds);
		table.loadDataIntoTable(this.tblData);
	}

	/**
	 * Tao calendar ngay sinh
	 */
	public void LoadNgaySinh() {
		if (this.txtNgaySinh == null) {
			this.txtNgaySinh = new JCalendar();
			this.pnlCalNgaySinh.add(this.txtNgaySinh);
		}
	}

	/**
	 * Tao calendar ngay vao lam
	 */
	public void LoadNgayVaoLam() {
		if (this.txtNgayVaoLam == null) {
			this.txtNgayVaoLam = new JCalendar();
			this.pnlCalNgayVaoLam.add(this.txtNgayVaoLam);
		}
	}

	/**
	 * Reset fields
	 */
	private void resetFields() {
		this.txtMaND.setEditable(true);
		this.txtMaND.setText("");
		this.txtHoTen.setText("");
		this.txtNgaySinh.setDate(new Date());
		this.txtNgayVaoLam.setDate(new Date());
		this.txtDiaChi.setText("");
		this.txtNoiSinh.setText("");
		this.txtDTDD.setText("");
		this.txtDTBan.setText("");
		this.txtEmail.setText("");
		this.txtChuyenMon.setText("");
		this.txtLuong.setText("");
	}

	/**
	 * Validate user input
	 * 
	 * @return true: valid / false: invalid
	 */
	private boolean validateInputData(AtomicReference<Object> errText) {
		if (this.txtHoTen.getText().trim().equals("")) {
			errText.set("Ban chua nhap ho ten");
			return false;
		}
		if (this.txtLuong.getText().trim().equals("")) {
			errText.set("Ban chua nhap luong");
			return false;
		}
		if (!Validator.isInteger(this.txtLuong.getText().trim())) {
			errText.set("Luong khong phai la so hop le");
			return false;
		}
		return true;
	}
}
